import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import {createPinia} from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import axios from 'axios'
import {useUserStore} from './stores/user'

// 配置axios
axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL || '/api'

// 添加请求拦截器
axios.interceptors.request.use(
    (config) => {
        const userStore = useUserStore()
        if (userStore.accessToken) {
            config.headers.Authorization = `Bearer ${userStore.accessToken}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 添加响应拦截器
axios.interceptors.response.use(
    (response) => {
        return response
    },
    async (error) => {
        const originalRequest = error.config
        const userStore = useUserStore()

        // 如果是401未授权错误且不是刷新令牌请求
        if (error.response?.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true

            // 尝试刷新令牌
            const refreshed = await userStore.refreshAccessToken()
            if (refreshed) {
                // 重新发送原始请求
                return axios(originalRequest)
            }
        }

        return Promise.reject(error)
    }
)

// 创建应用实例
const app = createApp(App)

// 安装插件
app.use(createPinia())
app.use(router)
app.use(ElementPlus)

// 全局注册axios
app.config.globalProperties.$axios = axios

// 路由守卫实现权限控制
router.beforeEach((to, from, next) => {
    const userStore = useUserStore()
    const isLoggedIn = userStore.isLoggedIn

    // 不需要登录的页面
    const whiteList = ['/login', '/register'] // 添加/register到白名单
    if (whiteList.includes(to.path)) {
        if (isLoggedIn && to.path === '/login') {
            // 已登录用户访问登录页时跳转到首页
            next('/')
        } else {
            next()
        }
        return
    }

    // 检查是否登录
    if (!isLoggedIn) {
        next('/login')
        return
    }

    // 检查管理员权限
    if (to.path === '/admin' && userStore.user?.role !== 'admin') {
        next('/404')
        return
    }

    next()
})

app.mount('#app')

